<?php
/**
 * Author: xx.com
 * Date: 2015-09-09
 */
namespace Admin\Controller;
use Admin\Logic\GoodsLogic;
use Think\AjaxPage;
use Think\Page;

class GoodsController extends BaseController {
    
    /**
     *  商品分类列表
     */
    public function categoryList(){                
        $GoodsLogic = new GoodsLogic();
        if ($this->shop_info){
            $shop_id = $this->shop_info['shop_id'];
            $where = "(shop_id = 0 OR shop_id = {$shop_id} )";
            $cat_list = $GoodsLogic->goods_cat_list('','','','',$where);
        }else{
            $shop_id = 0;
            $cat_list = $GoodsLogic->goods_cat_list();
//            var_dump($cat_list);die;
        }
        $this->assign('shop_id',$shop_id);
        $this->assign('cat_list',$cat_list);        
        $this->display();        
    }
    
    /**
     * 添加修改商品分类
     * 手动拷贝分类正则 ([\u4e00-\u9fa5/\w]+)  ('393','$1'), 
     * select * from tp_goods_category where id = 393
        select * from tp_goods_category where parent_id = 393
        update tp_goods_category  set parent_id_path = concat_ws('_','0_76_393',id),`level` = 3 where parent_id = 393
        insert into `tp_goods_category` (`parent_id`,`name`) values 
        ('393','时尚饰品'),
     */
    public function addEditCategory(){
        
            $GoodsLogic = new GoodsLogic();
            $shop = $this->shop_info;
            $shop_id = $shop ? $shop['shop_id'] : 0;
            
            // \var_dump($shop);
            if(IS_GET)
            {
                
                $cate_id = I('GET.id',0);

                if( $cate_id )
                {
                    $goods_category_info = D('GoodsCategory')->where([
                        'id' => $cate_id
                    ])->find();

                    if( ! $goods_category_info )
                    {
                        return $this->error('未找到相关分类');
                    }
                    
                    if( $shop_id > 0 )
                    {
                        if( $shop_id != $goods_category_info['shop_id'] )
                        return $this->error('非法操作');
                    }
                    else{
                        if( $shop_id != $goods_category_info['shop_id'] )
                        return $this->error('禁止修改商户私有分类');
                    }
                }
                
                $level_cat = $GoodsLogic->find_parent_cat($goods_category_info['id']); // 获取分类默认选中的下拉框
                
                $where['parent_id'] = 0;
                if ($this->shop_info){                   
                    $where['shop_id'] = ['IN','0,'.$shop_id]; // 支持公有和私有的分类                   
                }

                $cat_list = M('goods_category')->where($where)->select(); // 已经改成联动菜单

                $this->assign('shop_id',$shop_id);
                $this->assign('level_cat',$level_cat);
                $this->assign('cat_list',$cat_list);                 
                $this->assign('goods_category_info',$goods_category_info);      
                $this->display('_category');
                exit;
            }

            $GoodsCategory = D('GoodsCategory'); //

            $type = $_POST['id'] > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新                        
            //ajax提交验证
            if($_GET['is_ajax'] == 1)
            {
                C('TOKEN_ON',false);
                
                if(!$GoodsCategory->create(NULL,$type))// 根据表单提交的POST数据创建数据对象                 
                {
                    //  编辑
                    $return_arr = array(
                        'status' => -1,
                        'msg'   => '操作失败!',
                        'data'  => $GoodsCategory->getError(),
                    );
                    $this->ajaxReturn(json_encode($return_arr));
                }else {
                    //  form表单提交
                    C('TOKEN_ON',true);             
                    
                    $GoodsCategory->parent_id = $_POST['parent_id_1'];
                    $_POST['parent_id_2'] && ($GoodsCategory->parent_id = $_POST['parent_id_2']);                    
                    
                    if($GoodsCategory->id > 0 && $GoodsCategory->parent_id == $GoodsCategory->id)
                    {
                        //  编辑
                        $return_arr = array(
                            'status' => -1,
                            'msg'   => '上级分类不能为自己',
                            'data'  => '',
                        );
                        $this->ajaxReturn(json_encode($return_arr));                        
                    }

                    if($GoodsCategory->commission_rate > 100)
                    {
                        //  编辑
                        $return_arr = array(
                            'status' => -1,
                            'msg'   => '分佣比例不得超过100%',
                            'data'  => '',
                        );
                        $this->ajaxReturn(json_encode($return_arr));                        
                    }                    
                    if ($type == 2)
                    {
                        $GoodsCategory->save(); // 写入数据到数据库
                        $GoodsLogic->refresh_cat($_POST['id']);
                    }
                    else
                    {
                        $insert_id = $GoodsCategory->add(); // 写入数据到数据库
                        $where['id'] = $insert_id;
                        $shop['shop_id'] = $shop_id;
                        $GoodsCategory->where($where)->save($shop);
                        $GoodsLogic->refresh_cat($insert_id);
                    }
                    $return_arr = array(
                        'status' => 1,
                        'msg'   => '操作成功',
                        'data'  => array('url'=>U('Admin/Goods/categoryList')),
                    );
                    $this->ajaxReturn(json_encode($return_arr));

                }  
            }

    }
    
    /**
     * 获取商品分类 的筛选规格 复选框
     */
    public function ajaxGetSpecList(){
        $GoodsLogic = new GoodsLogic();
        $_REQUEST['category_id'] = $_REQUEST['category_id'] ? $_REQUEST['category_id'] : 0;
        $filter_spec = M('GoodsCategory')->where("id = ".$_REQUEST['category_id'])->getField('filter_spec');        
        $filter_spec_arr = explode(',',$filter_spec);        
        $str = $GoodsLogic->GetSpecCheckboxList($_REQUEST['type_id'],$filter_spec_arr);  
        $str = $str ? $str : '没有可筛选的商品规格';
        exit($str);        
    }
 
    /**
     * 获取商品分类 的筛选属性 复选框
     */
    public function ajaxGetAttrList(){
        $GoodsLogic = new GoodsLogic();
        $_REQUEST['category_id'] = $_REQUEST['category_id'] ? $_REQUEST['category_id'] : 0;
        $filter_attr = M('GoodsCategory')->where("id = ".$_REQUEST['category_id'])->getField('filter_attr');        
        $filter_attr_arr = explode(',',$filter_attr);        
        $str = $GoodsLogic->GetAttrCheckboxList($_REQUEST['type_id'],$filter_attr_arr);          
        $str = $str ? $str : '没有可筛选的商品属性';
        exit($str);        
    }    
    
    /**
     * 删除分类
     */
    public function delGoodsCategory(){
        // 判断子分类
        $GoodsCategory = M("GoodsCategory");
        $count = $GoodsCategory->where("parent_id = {$_GET['id']}")->fetchSql(0)->count("id");
        $count > 0 && $this->error('该分类下还有分类不得删除!',U('Admin/Goods/categoryList'));
        // 判断是否存在商品
        $goods_count = M('Goods')->where("cat_id = {$_GET['id']}")->count('1');
        $goods_count > 0 && $this->error('该分类下有商品不得删除!',U('Admin/Goods/categoryList'));
        // 删除分类
        $GoodsCategory->where("id = {$_GET['id']}")->delete();   
        $this->success("操作成功!!!",U('Admin/Goods/categoryList'));
    }
    
    
    /**
     *  商品列表
     */
    public function goodsList(){      
        $GoodsLogic = new GoodsLogic();        
        $brandList = $GoodsLogic->getSortBrands();
        $categoryList = $GoodsLogic->getSortCategory();
        $is_shop = 0;
        if ($this->shop_info)
        {
            $is_shop = 1;
        }
        $this->assign('categoryList',$categoryList);
        $this->assign('brandList',$brandList);
        $this->assign('is_shop', $is_shop);
        $this->display();                                           
    }
    
    /**
     *  商品列表
     */
    public function ajaxGoodsList(){            
        
        $where = ' 1 = 1 '; // 搜索条件
        I('intro')    && $where = "$where and ".I('intro')." = 1" ;        
        I('brand_id') && $where = "$where and brand_id = ".I('brand_id') ;
        (I('is_on_sale') !== '') && $where = "$where and is_on_sale = ".I('is_on_sale') ;                
        $cat_id = I('cat_id');
        // 关键词搜索               
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        if($key_word)
        {
            $where = "$where and (goods_name like '%$key_word%' or goods_sn like '%$key_word%')" ;
        }
        
        if($cat_id > 0)
        {
            $grandson_ids = getCatGrandson($cat_id); 
            $where .= " and cat_id in(".  implode(',', $grandson_ids).") "; // 初始化搜索条件
        }

        $is_shop = 0;
        $shopGoodsModel = M('shop_goods');
        if ($this->shop_info)
        {
            //$where .= " and shop_id = {$this->shop_info['shop_id']}";
            
//             var_dump($this->shop_info);
            // var_dump($where);

            $model = M('Goods');
            $where .=  ' and shop_goods_type = ' .$this->shop_info['goods_type'];

            $count = $model->where($where)->count();
            $Page = new AjaxPage($count, 10);
            /**  搜索条件下 分页赋值
             * foreach($condition as $key=>$val) {
             * $Page->parameter[$key]   =   urlencode($val);
             * }
             */
            $show = $Page->show();
            $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
            $goodsList = $model->where($where)->order($order_str)->limit($Page->firstRow . ',' . $Page->listRows)->select();

            foreach($goodsList as $key => $val){
                $shop_goods = $shopGoodsModel->where(array('shop_id'=>$this->shop_info['shop_id'], 'goods_id'=>$val['goods_id']))->find();
                if($shop_goods){
                    $goodsList[$key]['shop_store_count'] = $shop_goods['store_count'];
                    $goodsList[$key]['shop_on_sale'] = $shop_goods['shop_on_sale'];
                }else{
                    $goodsList[$key]['shop_store_count'] = 0;
                    $goodsList[$key]['shop_on_sale'] = 0;
                }
            }
            $is_shop = 1;
        }else{
            $model = M('Goods');
            $count = $model->where($where)->count();
            $Page = new AjaxPage($count, 10);
            /**  搜索条件下 分页赋值
             * foreach($condition as $key=>$val) {
             * $Page->parameter[$key]   =   urlencode($val);
             * }
             */
            $show = $Page->show();
            $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
            $goodsList = $model->where($where)->order($order_str)->limit($Page->firstRow . ',' . $Page->listRows)->select();

            foreach($goodsList as &$val){
                $val['real_store_count'] = $shopGoodsModel->alias('shop_goods')
                    ->join('ln_shop as shop on shop_goods.shop_id = shop.id', 'left')
                    ->where(array(
                        'shop_goods.goods_id'=>$val['goods_id'],
                        'shop_goods.shop_on_sale'=>1,
                        'shop.is_open'=>1
                    ))
                    ->sum('shop_goods.store_count');
            }
        }
        $catList = D('goods_category')->select();
        $catList = convert_arr_key($catList, 'id');
        $this->assign('catList',$catList);
        $this->assign('goodsList',$goodsList);
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('is_shop', $is_shop);
        $this->display();
    }


    /**
     * 添加修改商品
     */
    public function addEditGoods()
    {
        //if (!$this->shop_info)
        //{
        //    return $this->error("请使用商户账号登录");
        //}
        $GoodsLogic = new GoodsLogic();
        $Goods = D('Goods'); //
        $type = $_POST['goods_id'] > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新
        //ajax提交验证
        if (($_GET['is_ajax'] == 1) && IS_POST) {
            C('TOKEN_ON', false);
            if (!$Goods->create(NULL, $type))// 根据表单提交的POST数据创建数据对象
            {
                //  编辑
                $error = $Goods->getError();
                $error_msg = array_values($error);
                $return_arr = array(
                    'status' => -1,
                    'msg' => $error_msg[0],
                    'data' => $error,
                );
                $this->ajaxReturn(json_encode($return_arr));
            } else {
                //获取当前登录人的信息
                //  form表单提交
//              C('TOKEN_ON',true);
                // p($_POST);
                $time = $Goods->on_time = time(); // 上架时间
                //$Goods->cat_id = $_POST['cat_id_1'];
                $_POST['cat_id_2'] && ($Goods->cat_id = $_POST['cat_id_2']);
                $_POST['cat_id_3'] && ($Goods->cat_id = $_POST['cat_id_3']);

                $_POST['extend_cat_id_2'] && ($Goods->extend_cat_id = $_POST['extend_cat_id_2']);
                $_POST['extend_cat_id_3'] && ($Goods->extend_cat_id = $_POST['extend_cat_id_3']);
                //$Goods->shipping_area_ids = implode(',',$_POST['shipping_area_ids']);
                //$Goods->shipping_area_ids = $Goods->shipping_area_ids ? $Goods->shipping_area_ids : '';

                if ($type == 2) {
                    $goods_id = $_POST['goods_id'];

                    $goodsInfo = M('goods')->where([
                        "goods_id" => $goods_id
                    ])->field("goods_id")->find();

                    if( !$goodsInfo )
                    {
                        return $this->error("商品不存在");
                    }
                   /* if($this->admin_info['role_id'] == 8 || $this->admin_info['user_id'] != 0){
                        if (!$this->shop_info || $goodsInfo['shop_id']!=$this->shop_info['shop_id'])
                        {
                            return $this->error("非法操作");
                        }
                    }*/

                    $Goods->save(); // 写入数据到数据库
                    // 修改商品后购物车的商品价格也修改一下
                    M('cart')->where("goods_id = $goods_id and spec_key = ''")->save(array(
                            'market_price'=>$_POST['market_price'], //市场价
                            'goods_price'=>$_POST['shop_price'], // 本店价
                            'member_goods_price'=>$_POST['shop_price'], // 会员折扣价                        
                            ));
                    $Goods->afterSave($goods_id);
                } else {
                    //$shop_id =   1;
                    //if($this->admin_info['role_id'] == 8 || $this->admin_info['user_id'] != 0){
                        //$shop_id =   $this->shop_info['shop_id'];

                    //}

                    //$Goods->shop_id = $shop_id;
                    /*if($shop_id != 1){
                        $Goods->shop_goods_type = 1;
                    }*/

                    $goods_id = $insert_id = $Goods->add(); // 写入数据到数据库
                    $Goods->afterSave($goods_id);
                }

                $GoodsLogic->saveGoodsAttr($goods_id, $_POST['goods_type']); // 处理商品 属性

                $return_arr = array(
                    'status' => 1,
                    'msg' => '操作成功',
                    'data' => array('url' => U('Admin/Goods/goodsList')),
                );
                $this->ajaxReturn(json_encode($return_arr));
            }
        }

        $goodsInfo = M('Goods')->where('goods_id=' . I('GET.id', 0))->find();
        /*if( $this->shop_info )
        {
            if( $goodsInfo && $goodsInfo['shop_id'] != $this->shop_info['shop_id'] )
            {
                return $this->error("非法操作");
            }
        }*/

        //$cat_list = $GoodsLogic->goods_cat_list(); // 已经改成联动菜单
        $level_cat = $GoodsLogic->find_parent_cat($goodsInfo['cat_id']); // 获取分类默认选中的下拉框
        $level_cat2 = $GoodsLogic->find_parent_cat($goodsInfo['extend_cat_id']); // 获取分类默认选中的下拉框
        $cate_where['parent_id'] = 0;
        //$cate_where['shop_id'] = ['IN','0,'.$this->shop_info['shop_id']];
        $cat_list = M('goods_category')->where($cate_where)->select(); // 已经改成联动菜单
        /*$brandList = $GoodsLogic->getSortBrands([
            'shop_id' => ['IN','0,'.$this->shop_info['shop_id']]
        ]);*/
        $brandList = $GoodsLogic->getSortBrands();
        /*$goodsType = M("GoodsType")->where([
            'shop_id' => ['IN','0,'.$this->shop_info['shop_id']]
        ])->select();*/
        $goodsType = M("GoodsType")->select();
        $suppliersList = M("suppliers")->select();
        $this->assign('suppliersList',$suppliersList);
        $this->assign('level_cat', $level_cat);
        $this->assign('level_cat2', $level_cat2);
        $this->assign('cat_list', $cat_list);
        $this->assign('brandList', $brandList);
        $this->assign('goodsType', $goodsType);
        $this->assign('goodsInfo', $goodsInfo);  // 商品详情
        $goodsImages = M("GoodsImages")->where('goods_id =' . I('GET.id', 0))->select();
        $this->assign('goodsImages', $goodsImages);  // 商品相册
        $this->initEditor(); // 编辑器
        $this->display('_goods');
    } 
          
    /**
     * 商品类型  用于设置商品的属性
     */
    public function goodsTypeList(){
        $model = M("GoodsType");
        $where = NULL;
        if ($this->shop_info){
            $where['shop_id'] = ['IN','0,'.$this->shop_info['shop_id']];
            $count = $model->where($where)->count();
            $Page  = new Page($count,100);
            $show  = $Page->show();
            $goodsTypeList = $model->where($where)->order("id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
        }else{
            $count = $model->where($where)->count();
            $Page  = new Page($count,100);
            $show  = $Page->show();
            $goodsTypeList = $model->where($where)->order("id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
        }


        $this->assign('shop_id', $this->shop_info ? $this->shop_info['shop_id'] : 0 );
        $this->assign('show',$show);
        $this->assign('goodsTypeList',$goodsTypeList);
        $this->display('goodsTypeList');
    }
    
    
    /**
     * 添加修改编辑  商品属性类型
     */
    public  function addEditGoodsType(){        
            $_GET['id'] = $_GET['id'] ? $_GET['id'] : 0;            
            $model = M("GoodsType");
            $shop = $this->shop_info;
            $shop_id = $shop ? $shop['shop_id'] : 0;
            if(IS_POST)
            {
                    $model->create();
                    if($_GET['id'])
                        $model->save();
                    else
                    $ids =  $model->add();
                    $where['id'] = $ids;
                    $shop['shop_id'] = $shop_id;
                    $model->where($where)->save($shop);
                    $this->success("操作成功!!!",U('Admin/Goods/goodsTypeList'));               
                    exit;
            }
            $goodsType = $model->find($_GET['id']);
            if( $goodsType &&  $shop_id != $goodsType['shop_id'] ) return $this->error('非法操作');
            $this->assign('goodsType',$goodsType);
            $this->display('_goodsType');           
    }
    
    /**
     * 商品属性列表
     */
    public function goodsAttributeList(){
        $shop = $this->shop_info;
        $shop_id = $shop ? $shop['shop_id'] : 0;
        $where = NULL; // 搜索条件
        if ($shop) {
            $where['shop_id'] = ['IN','0,'.$this->shop_info['shop_id']];
            // $where['shop_id'] = $this->shop_info['shop_id'];
        }
        $goodsTypeList = M("GoodsType")->where($where)->select();
        $this->assign('goodsTypeList',$goodsTypeList);
        $this->display();
    }   
    
    /**
     *  商品属性列表
     */
    public function ajaxGoodsAttributeList(){            
        //ob_start('ob_gzhandler'); // 页面压缩输出
        $ty_where = $where = NULL; // 搜索条件  
        $type_id =   I('type_id', 0);                 
        if( $type_id )
        {
            $where['type_id'] = $type_id;
        }
        $shop = $this->shop_info;
        $shop_id = $shop ? $shop['shop_id'] : 0;
        if( $shop_id )
        {
            $ty_where['shop_id'] = ['IN','0,'.$this->shop_info['shop_id']];
            $where['shop_id'] = $this->shop_info['shop_id'];
            // $where['shop_id'] =  $ty_where['shop_id'];
        }

        $model = M('GoodsAttribute');
        $count = $model->where($where)->count();
        $Page = new AjaxPage($count, 13);
        $show = $Page->show();
        $goodsAttributeList = $model->where($where)->order('`order` desc,attr_id DESC')->limit($Page->firstRow . ',' . $Page->listRows)->select();

        $goodsTypeList = M("GoodsType")->where($ty_where)->getField('id,name');
        $attr_input_type = array(0=>'手工录入',1=>' 从列表中选择',2=>' 多行文本框');
        $this->assign('shop_id',$shop_id);
        $this->assign('attr_input_type',$attr_input_type);
        $this->assign('goodsTypeList',$goodsTypeList);        
        $this->assign('goodsAttributeList',$goodsAttributeList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();         
    }   
    
    /**
     * 添加修改编辑  商品属性
     */
    public  function addEditGoodsAttribute(){
        $shop = $this->shop_info;
        $shop_id = $shop ? $shop['shop_id'] : 0;

        $model = D("GoodsAttribute");                      
        $type = $_POST['attr_id'] > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新         
        $_POST['attr_values'] = str_replace('_', '', $_POST['attr_values']); // 替换特殊字符
        $_POST['attr_values'] = str_replace('@', '', $_POST['attr_values']); // 替换特殊字符            
        $_POST['attr_values'] = trim($_POST['attr_values']);
        $_POST['shop_id'] = $shop_id;

        if(($_GET['is_ajax'] == 1) && IS_POST)//ajax提交验证
        {                
            C('TOKEN_ON',false);
            if(!$model->create(NULL,$type))// 根据表单提交的POST数据创建数据对象                 
            {
                //  编辑
                $return_arr = array(
                    'status' => -1,
                    'msg'   => '提交不成功!',
                    'data'  => $model->getError(),
                );
                $this->ajaxReturn(json_encode($return_arr));
            }else {                   
                // C('TOKEN_ON',true); //  form表单提交
                if ($type == 2)
                {
                    $model->save(); // 写入数据到数据库                        
                }
                else
                {
                    $insert_id = $model->add(); // 写入数据到数据库
                }
                $return_arr = array(
                    'status' => 1,
                    'msg'   => '操作成功',                        
                    'data'  => array('url'=>U('Admin/Goods/goodsAttributeList')),
                );
                $this->ajaxReturn(json_encode($return_arr));
            }  
        }                
        // 点击过来编辑时                 
        $_GET['attr_id'] = $_GET['attr_id'] ? $_GET['attr_id'] : 0;
        $ty_where = NULL;
        if ($this->shop_info){
            $ty_where['shop_id'] = ['IN','0,'.$this->shop_info['shop_id']];
        }
        $goodsTypeList = M("GoodsType")->where($ty_where)->select();
        $goodsAttribute = $model->find($_GET['attr_id']);

        if( $goodsAttribute && $goodsAttribute['shop_id'] != $shop_id ) return $this->error('非法操作');

        $this->assign('goodsTypeList',$goodsTypeList);                   
        $this->assign('goodsAttribute',$goodsAttribute);
        $this->display('_goodsAttribute');           
    }  
    
    /**
     * 更改指定表的指定字段
     */
    public function updateField(){
        $primary = array(
                'goods' => 'goods_id',
                'goods_category' => 'id',
                'brand' => 'id',            
                'goods_attribute' => 'attr_id',
        		'ad' =>'ad_id',            
        );        
        $model = D($_POST['table']);
        $model->$primary[$_POST['table']] = $_POST['id'];
        $model->$_POST['field'] = $_POST['value'];        
        $model->save();   
        $return_arr = array(
            'status' => 1,
            'msg'   => '操作成功',                        
            'data'  => array('url'=>U('Admin/Goods/goodsAttributeList')),
        );
        $this->ajaxReturn(json_encode($return_arr));
    }
    /**
     * 动态获取商品属性输入框 根据不同的数据返回不同的输入框类型
     */
    public function ajaxGetAttrInput(){
        $shop = $this->shop_info;
        $shop_id = $shop ? $shop['shop_id'] : 0;
        $GoodsLogic = new GoodsLogic();
        $str = $GoodsLogic->getAttrInput($_REQUEST['goods_id'],$_REQUEST['type_id'],$shop_id);
        exit($str);
    }
        
    /**
     * 删除商品
     */
    public function delGoods()
    {
        $goods_id = $_GET['id'];
        $error = '';

        $goodsInfo = M("Goods")->where('goods_id ='.$goods_id)->find();

        if( !$goodsInfo )
        {
            $this->returnInfo(-1,"商品不存在");
        }

        if( $this->shop_info && $this->shop_info['shop_id'] != $goodsInfo['shop_id'] )
        {
            $this->returnInfo(-1,"非法操作");
        }
        
        // 判断此商品是否有订单
        $c1 = M('OrderGoods')->where("goods_id = $goods_id")->count('1');
        $c1 && $error .= '此商品有订单,不得删除! <br/>';
        
        
         // 商品团购
        $c1 = M('group_buy')->where("goods_id = $goods_id")->count('1');
        $c1 && $error .= '此商品有团购活动,不得删除! <br/>';   
        
         // 商品退货记录
        $c1 = M('return_goods')->where("goods_id = $goods_id")->count('1');
        $c1 && $error .= '此商品有退货记录,不得删除! <br/>';
        
        if($error)
        {
            $return_arr = array('status' => -1,'msg' =>$error,'data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);        
            $this->ajaxReturn(json_encode($return_arr));            
        }
        
        // 删除此商品        
        M("Goods")->where('goods_id ='.$goods_id)->delete();  //商品表
        M("cart")->where('goods_id ='.$goods_id)->delete();  // 购物车
        M("comment")->where('goods_id ='.$goods_id)->delete();  //商品评论
        M("goods_consult")->where('goods_id ='.$goods_id)->delete();  //商品咨询
        M("goods_images")->where('goods_id ='.$goods_id)->delete();  //商品相册
        M("spec_goods_price")->where('goods_id ='.$goods_id)->delete();  //商品规格
        M("spec_image")->where('goods_id ='.$goods_id)->delete();  //商品规格图片
        M("goods_attr")->where('goods_id ='.$goods_id)->delete();  //商品属性     
        M("goods_collect")->where('goods_id ='.$goods_id)->delete();  //商品收藏          
                     
        $return_arr = array('status' => 1,'msg' => '操作成功','data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);        
        $this->ajaxReturn(json_encode($return_arr));
    }
    
    /**
     * 删除商品类型 
     */
    public function delGoodsType()
    {
        // 判断 商品规格        
        $count = M("Spec")->where("type_id = {$_GET['id']}")->count("1");   
        $count > 0 && $this->error('该类型下有商品规格不得删除!',U('Admin/Goods/goodsTypeList'));
        // 判断 商品属性        
        $count = M("GoodsAttribute")->where("type_id = {$_GET['id']}")->count("1");   
        $count > 0 && $this->error('该类型下有商品属性不得删除!',U('Admin/Goods/goodsTypeList'));        
        // 删除分类
        M('GoodsType')->where("id = {$_GET['id']}")->delete();   
        $this->success("操作成功!!!",U('Admin/Goods/goodsTypeList'));
    }    

    /**
     * 删除商品属性
     */
    public function delGoodsAttribute()
    {         
       
        $item = M('GoodsAttribute')->where([
            'attr_id' => $_GET['id']
        ])->find();
        if( $this->shop_info && $this->shop_info['shop_id'] != $item['shop_id'] )
        {
            $this->returnInfo(-1,"非法操作");
        }

        // 判断 有无商品使用该属性
        $count = M("GoodsAttr")->where("attr_id = {$_GET['id']}")->count("1");   
        $count > 0 && $this->error('有商品使用该属性,不得删除!',U('Admin/Goods/goodsAttributeList'));

        // 删除 属性
        M('GoodsAttribute')->where([
            'attr_id' => $_GET['id']
        ])->delete();
        $this->success("操作成功!!!",U('Admin/Goods/goodsAttributeList'));
    }            
    
    /**
     * 删除商品规格
     */
    public function delGoodsSpec()
    {
        // 判断 商品规格项
        $count = M("SpecItem")->where("spec_id = {$_GET['id']}")->count("1");   
        $count > 0 && $this->error('清空规格项后才可以删除!',U('Admin/Goods/specList'));
        // 删除分类
        M('Spec')->where("id = {$_GET['id']}")->delete();   
        $this->success("操作成功!!!",U('Admin/Goods/specList'));
    } 
    
    /**
     * 品牌列表
     */
    public function brandList(){

        $shop = $this->shop_info;
        $shop_id = $shop ? $shop['shop_id'] : 0;

        $model = M("Brand");
        $where = NULL;
        $keyword = I('keyword', '');

        if( $keyword )
        {
            $where['name'] = "like '%$keyword%'";
        }

        if ($shop_id){
            $where['shop_id'] = ['IN','0,'.$shop_id];            
        }
        $count = $model->where($where)->count();
        $Page  = new Page($count,10);
        $brandList = $model->where($where)->order("`sort` asc")->limit($Page->firstRow.','.$Page->listRows)->select();

        if( IS_AJAX )
        {
            echo json_encode([
                'count' => $count,
                'list' => $brandList
            ]);
            return false;
        }

        $show  = $Page->show(); 
        $cat_list = M('goods_category')->where("parent_id = 0")->getField('id,name'); // 已经改成联动菜单
        $this->assign('shop_id',$shop_id);       
        $this->assign('cat_list',$cat_list);       
        $this->assign('show',$show);
        $this->assign('brandList',$brandList);
        $this->display('brandList');
    }
    
    /**
     * 添加修改编辑  商品品牌
     */
    public  function addEditBrand(){        
            $id = I('id');
            $model = M("Brand");
            $shop = $this->shop_info;
            $shop_id = $shop ? $shop['shop_id'] : 0;
            if(IS_POST)
            {
                $model->create();
                if($id)
                    $model->save();
                else
                    $ids = $model->add();
                    $where['id'] = $ids;
                    $shop['shop_id'] = $shop_id;
                    $model->where($where)->save($shop);
                $this->success("操作成功!!!",U('Admin/Goods/brandList',array('p'=>$_GET['p'])));
                exit;
            }
            $cat_where['parent_id'] = 0;

            if( $shop_id ) $cat_where['shop_id'] = ['IN','0,'.$shop_id];

            $cat_list = M('goods_category')->where($cat_where)->select(); // 已经改成联动菜单
           $this->assign('cat_list',$cat_list);           
           $brand = $model->find($id);
           $this->assign('brand',$brand);
           $this->display('_brand');           
    }    
    
    /**
     * 删除品牌
     */
    public function delBrand()
    {        
        // 判断此品牌是否有商品在使用
        $brand_ID = I('id', 0);
        $goods_count = M('Goods')->where(["brand_id"=>$brand_ID])->count('1');        
        if($goods_count)
        {
            $return_arr = array('status' => -1,'msg' => '此品牌有商品在用不得删除!','data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);        
            $this->ajaxReturn(json_encode($return_arr));            
        }
        $where['id'] = $brand_ID;
        if( $shop_id ) $where['shop_id'] = $shop_id;
        $model = M("Brand");
        $res = $model->where($where)->delete();

        if( $res )
        $return_arr = array('status' => 1,'msg' => '操作成功','data'  =>'',);   
        else
        $return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);

        $this->ajaxReturn(json_encode($return_arr));
    }      
    
    /**
     * 初始化编辑器链接     
     * 本编辑器参考 地址 http://fex.baidu.com/ueditor/
     */
    private function initEditor()
    {
        $this->assign("URL_upload", U('Admin/Ueditor/imageUp',array('savepath'=>'goods'))); // 图片上传目录
        $this->assign("URL_imageUp", U('Admin/Ueditor/imageUp',array('savepath'=>'article'))); //  不知道啥图片
        $this->assign("URL_fileUp", U('Admin/Ueditor/fileUp',array('savepath'=>'article'))); // 文件上传s
        $this->assign("URL_scrawlUp", U('Admin/Ueditor/scrawlUp',array('savepath'=>'article')));  //  图片流
        $this->assign("URL_getRemoteImage", U('Admin/Ueditor/getRemoteImage',array('savepath'=>'article'))); // 远程图片管理
        $this->assign("URL_imageManager", U('Admin/Ueditor/imageManager',array('savepath'=>'article'))); // 图片管理        
        $this->assign("URL_getMovie", U('Admin/Ueditor/getMovie',array('savepath'=>'article'))); // 视频上传
        $this->assign("URL_Home", "");
    }    
    
    
    
    /**
     * 商品规格列表    
     */
    public function specList(){

        $shop = $this->shop_info;
        $shop_id = $shop ? $shop['shop_id'] : 0;

        $where = NULL;

        if ($shop_id){
            $where['shop_id'] = ['IN', '0,'.$shop_id];            
        }

        $goodsTypeList = M("GoodsType")->where($where)->select();
        $this->assign('shop_id',$shop_id);   
        $this->assign('goodsTypeList',$goodsTypeList);
        $this->display();
    }
    
    
    /**
     *  商品规格列表
     */
    public function ajaxSpecList(){ 
        //ob_start('ob_gzhandler'); // 页面压缩输出
        $shop = $this->shop_info;
        $shop_id = $shop ? $shop['shop_id'] : 0;

        $where = NULL; // 搜索条件
        
        $type_id = I('type_id', 0);

        if( $type_id ) $where['type_id'] = $type_id;

        if(  $shop_id ){
            $where['shop_id'] = ['IN', '0,'.$shop_id];
        }
        // 关键词搜索               
        $model = D('spec');        
        $count = $model->where($where)->count();
        $Page = new AjaxPage($count, 13);
        $show = $Page->show();
        $specList = $model->where($where)->order('`type_id` desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $GoodsLogic = new GoodsLogic();        
        foreach($specList as $k => $v)
        {       // 获取规格项     
                $arr = $GoodsLogic->getSpecItem($v['id']);
                $specList[$k]['spec_item'] = implode(' , ', $arr);
        }
        $this->assign('shop_id',$shop_id);   
        $this->assign('specList',$specList);
        $this->assign('page',$show);// 赋值分页输出
        $goodsTypeList = M("GoodsType")->select(); // 规格分类
        $goodsTypeList = convert_arr_key($goodsTypeList, 'id');
        $this->assign('goodsTypeList',$goodsTypeList);        
        $this->display();         
    }      
    /**
     * 添加修改编辑  商品规格
     */
    public  function addEditSpec(){
                        
            $model = D("spec");                      
            $type = $_POST['id'] > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新             
            $shop = $this->shop_info;
            $shop_id = $shop ? $shop['shop_id'] : 0;
            if(($_GET['is_ajax'] == 1) && IS_POST)//ajax提交验证
            {                
                C('TOKEN_ON',false);
                if(!$model->create(NULL,$type))// 根据表单提交的POST数据创建数据对象                 
                {
                    //  编辑
                    $return_arr = array(
                        'status' => -1,
                        'msg'   => '',
                        'data'  => $model->getError(),
                    );
                    $this->ajaxReturn(json_encode($return_arr));
                }else {                   
                   // C('TOKEN_ON',true); //  form表单提交
                    if ($type == 2)
                    {
                        $model->save(); // 写入数据到数据库                        
                        $model->afterSave($_POST['id']);
                    }
                    else
                    {
                        $insert_id = $model->add(); // 写入数据到数据库
                        $where['id'] = $insert_id;
                        $shop['shop_id'] = $shop_id;
                        $model->where($where)->save($shop);
                        $model->afterSave($insert_id);
                    }                    
                    $return_arr = array(
                        'status' => 1,
                        'msg'   => '操作成功',                        
                        'data'  => array('url'=>U('Admin/Goods/specList')),
                    );
                    $this->ajaxReturn(json_encode($return_arr));
                }  
            }                
           // 点击过来编辑时                 
           $id = $_GET['id'] ? $_GET['id'] : 0;       
           $spec = $model->find($id);
           $GoodsLogic = new GoodsLogic();  
           $items = $GoodsLogic->getSpecItem($id);
           $spec[items] = implode(PHP_EOL, $items); 
           $this->assign('spec',$spec);

            if ($this->shop_info){
                $where['shop_id'] = ['IN', '0,'.$shop_id];
                $goodsTypeList = M("GoodsType")->where($where)->select();
            }else{
                $goodsTypeList = M("GoodsType")->select();
            }
           $this->assign('goodsTypeList',$goodsTypeList);           
           $this->display('_spec');           
    }  
    
    
    /**
     * 动态获取商品规格选择框 根据不同的数据返回不同的选择框
     */
    public function ajaxGetSpecSelect(){
        $goods_id = $_GET['goods_id'] ? $_GET['goods_id'] : 0;        
        $GoodsLogic = new GoodsLogic();
        //$_GET['spec_type'] =  13;
        $specList = D('Spec')->where("type_id = ".$_GET['spec_type'])->order('`order` desc')->select();
        foreach($specList as $k => $v)        
            $specList[$k]['spec_item'] = D('SpecItem')->where("spec_id = ".$v['id'])->order('id')->getField('id,item'); // 获取规格项                
        
        $items_id = M('SpecGoodsPrice')->where('goods_id = '.$goods_id)->getField("GROUP_CONCAT(`key` SEPARATOR '_') AS items_id");
        $items_ids = explode('_', $items_id);       
        
        // 获取商品规格图片                
        if($goods_id)
        {
           $specImageList = M('SpecImage')->where("goods_id = $goods_id")->getField('spec_image_id,src');                 
        }        
        $this->assign('specImageList',$specImageList);
        
        $this->assign('items_ids',$items_ids);
        $this->assign('specList',$specList);
        $this->display('ajax_spec_select');        
    }    
    
    /**
     * 动态获取商品规格输入框 根据不同的数据返回不同的输入框
     */    
    public function ajaxGetSpecInput(){     
         $GoodsLogic = new GoodsLogic();
         $goods_id = $_REQUEST['goods_id'] ? $_REQUEST['goods_id'] : 0;
         $spec_arr = $_POST['spec_arr'];
         // if(count($spec_arr) >= 3){
         //     $result = array('status'=> -1, 'msg'=>'最多选取两类规格！', 'data'=>'');
         // }else{
             $str = $GoodsLogic->getSpecInput($goods_id ,$spec_arr);
             $result = array('status'=> 1, 'msg'=>'', 'data'=>$str);
         // }
        $this->ajaxReturn($result);
    }
    
    /**
     * 删除商品相册图
     */
    public function del_goods_images()
    {
        $path = I('filename','');
        M('goods_images')->where("image_url = '$path'")->delete();
    }


    /**
     * 获取商品的各个规格及其价格
     */
    public function get_goods_specs()
    {
        $goods_id = I("goods_id");

        $model = M("spec_goods_price");

        $res = $model->where("goods_id = {$goods_id}")->select();

        if( IS_AJAX )
        {
            return $this->ajaxReturn($res);
        }

        $this->assign("specs",$res);
        $this->display();

    }

    public function detail(){
        $goods_id = I("get.id");
        $this->assign("goods_id",$goods_id);
        $this->display();
    }

    /**
    * 商品详情页
    */
    public function goodsInfo(){
 
        $goodsLogic = new \Home\Logic\GoodsLogic();
        $goods_id = I("get.id");
        $goods = M('Goods')->where("goods_id = $goods_id")->find();
        if(empty($goods) || ($goods['is_on_sale'] == 0)){
            $this->error('该商品已经下架');
        } 

        if($goods['brand_id']){
            $brnad = M('brand')->where("id =".$goods['brand_id'])->find();
            $goods['brand_name'] = $brnad['name'];
        }
        $goods_images_list = M('GoodsImages')->where("goods_id = $goods_id")->select(); // 商品 图册
        $goods_attribute = M('GoodsAttribute')->getField('attr_id,attr_name'); // 查询属性
        $goods_attr_list = M('GoodsAttr')->where("goods_id = $goods_id")->select(); // 查询商品属性表
        $filter_spec = $goodsLogic->get_spec($goods_id);
        //商品是否正在限时抢购促销中
        if($goods['prom_type'] == 1)
        {
            $goods['flash_sale'] = get_goods_kill($goods['goods_id']);
            $flash_sale = M('flash_sale')->where("id = {$goods['prom_id']}")->find();
            $this->assign('flash_sale',$flash_sale);
        }

        if($goods['prom_type'] == 3){
            $goods['promotion'] = get_goods_promotion($goods['goods_id']);
        }

        $freight_free = tpCache('shopping.freight_free'); // 全场满多少免运费
        $spec_goods_price  = M('spec_goods_price')->where("goods_id = $goods_id")->getField("key,price,store_count"); // 规格 对应 价格 库存表
        M('Goods')->where("goods_id=$goods_id")->save(array('click_count'=>$goods['click_count']+1 )); //统计点击数
        $commentStatistics = $goodsLogic->commentStatistics($goods_id);// 获取某个商品的评论统计
        $point_rate = tpCache('shopping.point_rate');
        //重新设置商品的评论数--之前是获取的所有评论数，后台未审核通过的评论也统计进去了-liuyang
        $goods['comment_count'] = $commentStatistics['c0'];
        //获取未选定规格商品信息
        $filter_spec2 = $goodsLogic->get_spec_other($goods_id);
        //获取选定规格商品信息
        $item_array = $goodsLogic->getSpecInput($goods_id, $filter_spec2);

        $after_sale = M('article')->where(array('article_id'=> 1))->find();

        //默认运费
        $shipping_code = tpCache('shopping.default_shipping');
        $shipping_area_id = M("ShippingArea")->where("shipping_code = '$shipping_code' and is_default = 1")->getField('shipping_area_id');
        if(!$shipping_area_id){
            $shipping_area_id = M("ShippingArea")->where("shipping_code = '$shipping_code'")->getField('shipping_area_id');
        }
        $shipping_config = M('ShippingArea')->where(array('shipping_area_id' => $shipping_area_id))->getField('config');
        $shipping_config  = unserialize($shipping_config);
        $shipping_config['money'] = $shipping_config['money'] ? $shipping_config['money'] : 0;

        $this->assign('freight_free', $freight_free);// 全场满多少免运费
        $this->assign('spec_goods_price', json_encode($spec_goods_price,true)); // 规格 对应 价格 库存表
        // $this->assign('navigate_goods',navigate_goods($goods_id,1));// 面包屑导航
        $this->assign('navigate_goods',[]);// 面包屑导航
        $this->assign('commentStatistics',$commentStatistics);//评论概览
        $this->assign('goods_attribute',$goods_attribute);//属性值
        $this->assign('goods_attr_list',$goods_attr_list);//属性列表
        $this->assign('filter_spec',$filter_spec);//规格参数
        $this->assign('goods_images_list',$goods_images_list);//商品缩略图
        $this->assign('siblings_cate',$goodsLogic->get_siblings_cate($goods['cat_id']));//相关分类
        $this->assign('look_see',$goodsLogic->get_look_see($goods));//看了又看
        $this->assign('goods',$goods);
        $this->assign('point_rate',$point_rate);
        $this->assign('item_array', $item_array);
        $this->assign('after_sale', $after_sale);
        $this->assign('config_money', $shipping_config['money']);
        $str = $goodsLogic->getSpecInput($goods_id, $filter_spec);
        $this->assign('str', $str);
        $this->display('goodsinfo');
    }
}